﻿#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <string.h>
#include <math.h>
#include <unordered_map>
#include <mutex>
#include <condition_variable>
#include <functional>
using namespace std;

class ThreadPool{
private:
	std::vector<std::thread> workers;
	std::queue<std::function<void()>> tasks;
	std::mutex queue_mutex;
	std::condition_variable condition;
	bool stop;

public:
	ThreadPool(size_t num_threads) : stop(false) {
		// 创建num_threads个线程
		for(size_t i = 0;i < num_threads; ++i) {
			workers.emplace_back([this]() {
				while(true) {
					std::function<void()> task;
					{
						std::unique_lock<std::mutex> lock(queue_mutex);
						condition.wait(lock, [this]() { return stop || !tasks.empty(); });
						if(stop && tasks.empty()) return;
						task = std::move(tasks.front());
						tasks.pop();
					}
					task();// 执行任务
				}
			});
		}
	}

	~ThreadPool() {
		{
			std::unique_lock<std::mutex> lock(queue_mutex);
			stop = true;
		}
		condition.notify_all();
		for(auto & worker : workers) {
			worker.join();
		}
	}

	// 提交任务
	template<typename F>
	void enqueue(F&& f) {
		{
			std::unique_lock<std::mutex> lock(queue_mutex);
			tasks.emplace(std::forward<F>(f));
		}
		condition.notify_one();
	}
};

int main() {
	ThreadPool pool(4);// 创建4个线程的线程池
	for(int i = 0; i < 8; ++i) {
		pool.enqueue([i]() {
			std::cout<< "Task " << i << " executed by thread " << std::this_thread::get_id() << "\n";
			std::this_thread::sleep_for(std::chrono::milliseconds(100));// 模拟工作
			});
	}
	std::this_thread::sleep_for(std::chrono::seconds(1));// 等待任务完成
	return 0;
}
